<template>
  <div id="container" ref="canvasref">
  </div>
</template>
<!-- <script src="./static/SharkViewer/lib/three.min.js"></script> -->
<!-- <script src="./static/SharkViewer/lib/shark_viewer.js"></script> -->
<script>
// import {THREE} from "../../static/SharkViewer/lib/three.min.js"
// import * as THREE from "three";
// import {sharkViewer} from "../../static/SharkViewer/lib/shark_viewer.js"
// const THREE = require('three')
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";
import { STLLoader } from "three/examples/jsm/loaders/STLLoader";
// import SharkViewer, { swcParser } from sharkViewer;

import axios from 'axios'
import { globalBus } from './globalBus';



export default {
  data: () => ({
    controls: {
      scene: null,
      camera: null,
      renderer: null,
      // rotationSpeed: 0.02
    },
    controller: null
  }),
  created() {
    var controller = {
      BackgroundColor: 0xffffff,
      BrainColor: 0xaaaaaa,
      AllRegionPoint: false,
      PointSize: 100,
      Render: true
    };
    this.controller = controller;
    const gui = new dat.GUI();
    gui.domElement.style.position = 'absolute';
    gui.domElement.style.right = '10px';
    gui.domElement.style.top = '80px';
    var h = gui.addFolder("Setting");
    h.addColor(controller, 'BackgroundColor').onChange(this.update);
    h.addColor(controller, 'BrainColor').onChange(this.brainupdate);
    h.add(controller, 'AllRegionPoint').onChange(this.allsoma);
    h.add(controller, 'PointSize').onChange(this.update);
    h.add(controller, 'Render').onChange(this.RenderUpdate);
    gui.addFolder("Properties");
    // debugger
    this.$nextTick(() => {
      this.init()
    })
  },
  mounted() {

    window.onresize = () => {
      const width = this.$refs.canvasref.clientWidth;
      const height = this.$refs.canvasref.clientHeight;
      window.s.setSize(width, height);
      window.s.render();

    }

  },
  methods: {
    randomHexColor() { //随机生成十六进制颜色
      let x = (Math.random() * (1.0 - 0.5)) + 0.5;
      // debugger
      return '#' + ('00000' + ((x * 0x1000000 << 0)).toString(16)).substr(-6);
    },
    update() {
      window.s.setBackground(this.controller.BackgroundColor);
      var n = window.s.scene.children;
      for (var i = 0; i < n.length; i++)
        n[i].material.uniforms.scale = { value: this.controller.PointSize };
      // debugger
      window.s.trackControls.update();

    },
    brainupdate() {
      var brain = window.s.scene.getObjectByName("root");
      brain.children[0].material.uniforms.color = { type: "c", value: new THREE.Color(this.controller.BrainColor) }

      window.s.trackControls.update();

    },
    RenderUpdate(value) {
        window.s.unloadCompartment("root");

      if (!value) {
      axios.get('./static/allobj/997.obj')
        .then(res => {
          // debugger
          s.loadCompartment0('root', '#aaaaaa', res.data); //
          s.centerCameraAroundCompartment(s.scene.getObjectByName('root')); //将返回值赋给上述已定义的本地变量
          window.s.trackControls.update()
        })


      } else {
      axios.get('./static/allobj/997.obj')
        .then(res => {
          // debugger
          s.loadCompartment('root', '#aaaaaa', res.data); //
          s.centerCameraAroundCompartment(s.scene.getObjectByName('root')); //将返回值赋给上述已定义的本地变量
          window.s.trackControls.update()
        })

      }
      window.s.trackControls.update();

    },
    allsoma(value) {
      console.log("allsoma", value)
      if (value) {
        axios.get('./static/cwz.json')
          .then(res => {
            // debugger
            for (var i = res.data.length - 1; i >= 0; i--) {
              var geometry = new THREE.SphereBufferGeometry(1, 20, 20);
              var col = new THREE.Color(this.randomHexColor());
              var center = new THREE.Vector3(res.data[i].B * -1000 + 5472, res.data[i].D * 1000, res.data[i].L * 1000 + 5700)

              var mat = new THREE.Matrix4();
              mat.makeScale(this.controller.PointSize, this.controller.PointSize, this.controller.PointSize);
              const material = new THREE.ShaderMaterial({
                uniforms: {
                  ratio: {
                    value: 0.0
                  },
                  color: {
                    value: col
                  },
                  center: {
                    value: center
                  },
                  scale: {
                    value: this.controller.PointSize
                  }
                },
                vertexShader: "uniform float scale;uniform vec3 center;varying vec3 light;varying vec3 vNormal;void main() {gl_Position = projectionMatrix * modelViewMatrix * vec4( (position*scale), 1.0 );vNormal=normalize((modelViewMatrix*vec4(normal.xyz, 0.0)).xyz);light = normalize( vec4(0.0, 0.0, 1.0,1.0)).xyz;}",
                fragmentShader: "varying vec3 light;varying vec3 vNormal; uniform vec3 color;void main() {   float diffuse = max((dot((light), (vNormal.xyz))), 0.0)*0.9;gl_FragColor = vec4( color*diffuse*2.0, 1.0);     }"
              });
              // debugger
              var sphere = new THREE.Mesh(geometry, material);
              sphere.position.x = center.x;
              sphere.position.y = center.y;
              sphere.position.z = center.z;
              sphere.name = 'allsoma';
              window.s.scene.add(sphere);
            }

            window.s.render();
            window.s.trackControls.update();
          });
      } else {
        for (var i = window.s.scene.children.length - 1; i >= 0; i--) {
          if (window.s.scene.children[i].name != "root")
            window.s.scene.remove(window.s.scene.children[i]);

        }
        window.s.trackControls.update()
      }
    },
    onSelectNode(e, t, n) {
      // debugger
      for (var i = t.object.parent.parent.children.length - 1; i >= 0; i--) {
        if (t.object.parent.parent.children[i].isNeuron) {
          t.object.parent.parent.children[i].children[0].material.uniforms.select = { value: 0 };
          t.object.parent.parent.children[i].children[0].material.uniforms.selectcount = { value: 1 };
        }
        // console.log(.name)
      }
      t.object.material.uniforms.select = { value: 1 };
      window.s.trackControls.update()
      globalBus.$emit("highlightNeuron", [e.slice(0, -7), e.slice(-7)])
    },
    init() {

      let s = new sharkViewer.default({
        animated: false,
        mode: 'skeleton',
        dom_element: document.getElementById('container'),

        showAxes: 10000,
        maxVolumeSize: 50000,
        backgroundColor: 0xffffff,
        // cameraChangeCallback: () => {},
        on_select_node: (e, t, n) => this.onSelectNode(e, t, n),
      });
      window.s = s;
      s.init();
      // s.animate();
      // s.addAxes();

      s.showAxes && (s.axesCamera.position.copy(s.camera.position),
        s.axesCamera.position.sub(s.trackControls.target),
        s.axesCamera.position.setLength(300),
        s.axesCamera.lookAt(s.axesScene.position));


      axios.get('./static/allobj/997.obj')
        .then(res => {
          // debugger
          s.loadCompartment('root', '#aaaaaa', res.data); //
          s.centerCameraAroundCompartment(s.scene.getObjectByName('root')); //将返回值赋给上述已定义的本地变量
          window.s.trackControls.update()
        })


      s.render();


    },


  }
}

</script>
<style scoped>
div {

  height: calc(100% - 101px);

  background: #000000;
  color: #ffffff;
}

</style>
